package com.wuh.controller;

import com.wuh.model.ClassAttachment;
import com.wuh.service.ClassAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
public class ClassAttachmentController {

    @Autowired
    public ClassAttachmentService classAttachmentService;


    /**
     * 动态模糊查询公开课文件
     *
     * @param classAttachment
     * @return
     */
    @RequestMapping("/findAttachmentAll")
    public ModelAndView findAttachmentAll(ClassAttachment classAttachment) {
        ModelAndView mv = new ModelAndView();
        List<ClassAttachment> classAttachments = classAttachmentService.findAttachmentAll(classAttachment);
        mv.addObject("classAttachments", classAttachments);
        mv.setViewName("redirect:/toTeacherMyClass");
        return mv;
    }


    /**
     * 添加公开课文件
     *
     * @param classAttachment
     * @return
     */
    @RequestMapping("/addClassAttachment")
    public String addClassAttachment(MultipartFile upAttachment, ClassAttachment classAttachment) {
        if (!upAttachment.isEmpty()) {
            //获取项目文件地址
            String filepath = new String("src/main/resources/" + "static/classAttachment");
            File staticFile = new File(filepath);
            //设置文件名
            String fileName = upAttachment.getOriginalFilename();  //获取原文件名
            classAttachment.setAttachmentName(fileName);
            String uuid = UUID.randomUUID().toString().replace("-", ""); //把文件的名称设置唯一值，uuid
            fileName = uuid + "_" + fileName; //文件名
            //图片保存全路径
            String uploadPath = staticFile.getAbsolutePath() + File.separator + fileName;
            File targetFile = new File(uploadPath);
            //上传文件
            if (!targetFile.exists()) {
                targetFile.mkdirs();
                System.out.println("创建新文件夹");
            } else {
                System.out.println("文件夹存在");
            }
            try {
                upAttachment.transferTo(targetFile);  //上传
                System.out.println("上传成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //存储文件访问地址
            fileName = "/classAttachment\\" + fileName;
            //设置文件访问地址
            classAttachment.setAttachmentUrl(fileName);
            classAttachmentService.addClassAttachment(classAttachment);
            return "person/tercher_myclass";
        } else {
            classAttachmentService.addClassAttachment(classAttachment);
            return "person/tercher_myclass";
        }
    }


    /**
     * 公开课文件下载
     */
    @RequestMapping(value = "/classAttachmentDownload", method = RequestMethod.GET)
    public void download(HttpServletResponse response,String attachmentUrl){

        downloadFile(attachmentUrl,"课程文件.jpg",response);

//
    }


    /**
     * 下载文件方法
     */
    public void downloadFile(String filename, String downname, HttpServletResponse response) {
        String filepath = new String("src/main/resources/" + "static");
        File staticFile = new File(filepath);
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
        // 设置下载文件使用的报头
            response.setHeader("Content-Type", "application/x-msdownload");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(downname.getBytes("UTF-8"), "ISO8859-1"));
          // 读入文件
            in = new FileInputStream(staticFile.getAbsolutePath() +  File.separator + filename);
        // 得到响应对象的输出流，用于向客户端输出二进制数据
            out = response.getOutputStream();
            out.flush();

            int aRead = 0;
            byte b[] = new byte[1024];
            while ((aRead = in.read(b)) != -1 && in != null) {
                out.write(b, 0, aRead);
            }
            out.flush();
            in.close();
            out.close();
            System.out.println("下载成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }


    }
